import React, { useState, useEffect, useCallback, useMemo } from "react";
import {
  Card,
  CardContent,
  CardHeader,
  CardTitle,
  CardDescription,
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Label } from "@/components/ui/label";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Badge } from "@/components/ui/badge";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Checkbox } from "@/components/ui/checkbox";
import { riskTypeS } from "@/public/riskTypeLabels";

import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogFooter,
  DialogDescription,
} from "@/components/ui/dialog";
import { ScrollArea } from "@/components/ui/scroll-area";
import { useToast } from "@/components/ui/use-toast";
import { SafetyRiskPointAPI } from "@/api/SafetyRiskPoint";
import { RecommendationsAPI } from "@/api/Recommendations";

import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from "@/components/ui/table";
import {
  Plus,
  Trash2,
  Shield,
  Zap,
  Car,
  Train,
  Ship,
  AlertTriangle,
  Info,
  Lightbulb,
  Sparkles,
  BookOpen,
  Check,
  FileText,
  Settings,
  Loader2,
  Wrench,
  Leaf,
  Cloud,
  CheckSquare,
  Edit3,
  ChevronDown,
  ChevronUp,
  MapPin,
} from "lucide-react";
import { Switch } from "@/components/ui/switch";

function RiskImportModal({ isOpen, onClose, onImport, availableRisks = [] }) {
  const [selectedRisks, setSelectedRisks] = useState(new Set());
  const [filterType, setFilterType] = useState("all");
  const [filterCategory, setFilterCategory] = useState("all");
  const [searchTerm, setSearchTerm] = useState("");

  const filteredRisks = availableRisks.filter((risk) => {
    if (!risk) return false;
    const matchesSearch =
      searchTerm === "" ||
      (risk.riskName &&
        risk.riskName.toLowerCase().includes(searchTerm.toLowerCase())) ||
      (risk.riskDescription &&
        risk.riskDescription.toLowerCase().includes(searchTerm.toLowerCase()));

    const matchesType =
      filterType === "all" ||
      (risk.riskType &&
        Array.isArray(risk.riskType) &&
        risk.riskType.includes(filterType));

    const matchesCategory =
      filterCategory === "all" ||
      (risk.primaryCategory && risk.primaryCategory === filterCategory);

    return matchesSearch && matchesType && matchesCategory;
  });

  const handleToggleRisk = (id) => {
    if (!id) return;

    setSelectedRisks((prev) => {
      const newSet = new Set(prev);
      if (newSet.has(id)) {
        newSet.delete(id);
      } else {
        newSet.add(id);
      }
      return newSet;
    });
  };

  const handleConfirmImport = () => {
    const risksToImport = availableRisks.filter(
      (risk) => risk && risk.id && selectedRisks.has(risk.id)
    );

    if (risksToImport.length > 0) {
      onImport(risksToImport);
    }
    handleClose();
  };

  const handleClose = () => {
    setSelectedRisks(new Set());
    setFilterType("all");
    setFilterCategory("all");
    setSearchTerm("");
    onClose();
  };

  return (
    <Dialog open={isOpen} onOpenChange={handleClose}>
      <DialogContent className="max-w-4xl h-[90vh] flex flex-col">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <BookOpen className="w-5 h-5 text-blue-600" />
            从知识库导入风险点
          </DialogTitle>
          <DialogDescription>
            选择需要导入的风险点，系统将自动添加对应的控制措施
          </DialogDescription>
        </DialogHeader>

        <div className="grid grid-cols-1 md:grid-cols-3 gap-4 p-4 bg-gray-50 rounded-lg mt-4">
          <div>
            <Label htmlFor="search">搜索风险</Label>
            <Input
              id="search"
              placeholder="输入关键词搜索..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
            />
          </div>

          <div>
            <Label htmlFor="filterType">风险类型</Label>
            <Select value={filterType} onValueChange={setFilterType}>
              <SelectTrigger>
                <SelectValue placeholder="选择风险类型" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">全部类型</SelectItem>
                {riskTypeS.map((type) => (
                  <SelectItem key={type.key} value={type.key}>
                    {type.label}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>

          <div>
            <Label htmlFor="filterCategory">作业类别</Label>
            <Select value={filterCategory} onValueChange={setFilterCategory}>
              <SelectTrigger>
                <SelectValue placeholder="选择作业类别" />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="all">全部类别</SelectItem>
                <SelectItem value="foundations">基础工程</SelectItem>
                <SelectItem value="towerAssembly">杆塔组立</SelectItem>
                <SelectItem value="stringingWorks">架线工程</SelectItem>
                <SelectItem value="liveLineWork">带电作业</SelectItem>
                <SelectItem value="transportation">运输工程</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </div>

        <div className="flex-1 mt-4 min-h-0">
          <ScrollArea className="h-full border rounded-lg">
            <div className="p-4 space-y-2">
              {filteredRisks.length > 0 ? (
                filteredRisks.map((risk) => (
                  <div
                    key={risk.id}
                    className={`p-3 border rounded-lg cursor-pointer transition-colors ${
                      selectedRisks.has(risk.id)
                        ? "bg-blue-50 border-blue-300"
                        : "bg-white hover:bg-gray-50"
                    }`}
                    onClick={() => handleToggleRisk(risk.id)}
                  >
                    <div className="flex items-start gap-3">
                      <Checkbox
                        checked={selectedRisks.has(risk.id)}
                        onCheckedChange={() => handleToggleRisk(risk.id)}
                      />
                      <div className="flex-1">
                        <div className="flex items-center gap-2 mb-1">
                          <h4 className="font-medium text-gray-900">
                            {risk.riskName}
                          </h4>
                        </div>
                        <p className="text-sm text-gray-600 mb-2">
                          {risk.riskDescription}
                        </p>
                        <div className="flex flex-wrap gap-1">
                          {Array.isArray(risk.riskType) &&
                            risk.riskType.map((typeKey) => {
                              const riskType = riskTypeS.find(
                                (item) => item.key === typeKey
                              );
                              const displayText = riskType?.label || typeKey;
                              return (
                                <Badge
                                  key={typeKey}
                                  variant="secondary"
                                  className="text-xs"
                                >
                                  {displayText}
                                </Badge>
                              );
                            })}
                        </div>
                        {Array.isArray(risk.controlMeasures) &&
                          risk.controlMeasures.length > 0 && (
                            <div className="mt-2">
                              <p className="text-xs text-gray-500">
                                控制措施:{" "}
                                {risk.controlMeasures.slice(0, 2).join("；")}
                                {risk.controlMeasures.length > 2 && "..."}
                              </p>
                            </div>
                          )}
                      </div>
                    </div>
                  </div>
                ))
              ) : (
                <div className="text-center py-12">
                  <AlertTriangle className="w-12 h-12 text-gray-300 mx-auto mb-4" />
                  <p className="text-gray-500">未找到匹配的风险点</p>
                  <p className="text-sm text-gray-400 mt-1">尝试调整筛选条件</p>
                </div>
              )}
            </div>
          </ScrollArea>
        </div>

        <DialogFooter className="mt-4">
          <div className="flex items-center gap-4 w-full">
            <div className="flex-1 text-sm text-gray-600">
              已选择 {selectedRisks.size} 个风险点
            </div>
            <Button variant="outline" onClick={handleClose}>
              取消
            </Button>
            <Button
              onClick={handleConfirmImport}
              disabled={selectedRisks.size === 0}
            >
              <Check className="w-4 h-4 mr-2" />
              导入风险点 ({selectedRisks.size})
            </Button>
          </div>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}

// 方案级措施编辑器组件
const SchemeLevelMeasuresEditor = ({
  title,
  measures,
  onUpdate,
  icon: Icon,
  placeholder,
}) => {
  const [isExpanded, setIsExpanded] = useState(false);

  const currentMeasures = useMemo(() => {
    return Array.isArray(measures) ? measures : [];
  }, [measures]);

  const handleAddMeasure = useCallback(
    (e) => {
      e.stopPropagation();
      const newMeasures = [...currentMeasures, ""];
      onUpdate(newMeasures);
      if (!isExpanded) {
        setIsExpanded(true);
      }
    },
    [currentMeasures, onUpdate, isExpanded]
  );

  const handleUpdateMeasure = useCallback(
    (index, value) => {
      const newMeasures = [...currentMeasures];
      newMeasures[index] = value;
      onUpdate(newMeasures);
    },
    [currentMeasures, onUpdate]
  );

  const handleRemoveMeasure = useCallback(
    (index) => {
      const newMeasures = currentMeasures.filter((_, i) => i !== index);
      onUpdate(newMeasures);
    },
    [currentMeasures, onUpdate]
  );

  return (
    <Card>
      <CardHeader
        className="cursor-pointer hover:bg-gray-50 transition-colors"
        onClick={() => setIsExpanded(!isExpanded)}
      >
        <CardTitle className="flex items-center justify-between">
          <span className="flex items-center gap-2">
            <Icon className="w-5 h-5 text-blue-600" />
            {title}
            <Badge
              variant="outline"
              className="bg-blue-50 text-blue-700 border-blue-200"
            >
              {currentMeasures.length} 项
            </Badge>
          </span>
          <div className="flex items-center gap-3">
            <Button onClick={handleAddMeasure} variant="outline" size="sm">
              <Plus className="w-4 h-4 mr-2" />
              添加
            </Button>
            {isExpanded ? (
              <ChevronUp className="w-5 h-5 text-gray-500" />
            ) : (
              <ChevronDown className="w-5 h-5 text-gray-500" />
            )}
          </div>
        </CardTitle>
      </CardHeader>
      {isExpanded && (
        <CardContent className="space-y-4 pt-4 border-t">
          {currentMeasures.length === 0 ? (
            <div className="text-center py-8 text-gray-500 border-2 border-dashed border-gray-300 rounded-lg">
              <Icon className="w-12 h-12 mx-auto mb-4" />
              <p>暂无{title}</p>
              <p className="text-sm">{placeholder}</p>
            </div>
          ) : (
            currentMeasures.map((measure, index) => (
              <div
                key={`${title}-measure-${index}`}
                className="flex items-center gap-3 p-3 bg-gray-50 rounded-lg"
              >
                <span className="text-sm font-medium text-gray-600 min-w-8">
                  {index + 1}.
                </span>
                <Input
                  value={measure || ""}
                  onChange={(e) => handleUpdateMeasure(index, e.target.value)}
                  placeholder={`输入${title}...`}
                  className="flex-1"
                />
                <Button
                  variant="ghost"
                  size="icon"
                  onClick={() => handleRemoveMeasure(index)}
                  className="text-red-500 hover:text-red-700 hover:bg-red-50"
                >
                  <Trash2 className="w-4 h-4" />
                </Button>
              </div>
            ))
          )}
        </CardContent>
      )}
    </Card>
  );
};

// 天气影响分析组件
const WeatherAnalysisEditor = ({ scheme, onUpdate }) => {
  return (
    <Card>
      <CardHeader>
        <CardTitle className="flex items-center gap-2">
          <Cloud className="w-5 h-5 text-blue-600" />
          天气影响分析与应对措施
        </CardTitle>
      </CardHeader>
      <CardContent className="space-y-4">
        <div>
          <Label htmlFor="weather-requirements">天气要求与限制条件</Label>
          <Textarea
            id="weather-requirements"
            value={scheme.weatherRequirements || ""}
            onChange={(e) => onUpdate({ weatherRequirements: e.target.value })}
            placeholder="描述施工对天气的要求，如风速限制、降雨限制、能见度要求等..."
            rows={3}
          />
        </div>
        <div>
          <Label htmlFor="weather-measures">恶劣天气应对措施</Label>
          <Textarea
            id="weather-measures"
            value={scheme.weatherResponseMeasures || ""}
            onChange={(e) =>
              onUpdate({ weatherResponseMeasures: e.target.value })
            }
            placeholder="制定遇到恶劣天气时的具体应对措施和停工标准..."
            rows={4}
          />
        </div>
      </CardContent>
    </Card>
  );
};

function RiskControlManager({ scheme, onUpdate, crossingPoint, project }) {
  const [isAnalyzing, setIsAnalyzing] = useState(false);
  const [showImportModal, setShowImportModal] = useState(false);
  const [availableRisks, setAvailableRisks] = useState([]);
  const [loadingRisks, setLoadingRisks] = useState(false);
  const [editingRowId, setEditingRowId] = useState(null);
  const { toast } = useToast();

  const riskItems = Array.isArray(scheme?.riskControlItems)
    ? scheme.riskControlItems
    : [];

  // 一级任务中文映射
  const primaryTaskOptions = [
    { value: "foundations", label: "基础工程" },
    { value: "towerAssembly", label: "杆塔组立" },
    { value: "stringingWorks", label: "架线工程" },
    { value: "liveLineWork", label: "带电作业" },
    { value: "transportation", label: "运输作业" },
    { value: "environmental", label: "环境作业" },
    { value: "management", label: "管理作业" },
  ];

  // 获取一级任务的中文显示
  const getPrimaryTaskLabel = (value) => {
    const option = primaryTaskOptions.find((opt) => opt.value === value);
    return option ? option.label : value || "-";
  };

  // 将controlMeasures从数组转换为字符串进行显示
  const getControlMeasuresDisplay = (controlMeasures) => {
    if (Array.isArray(controlMeasures)) {
      return controlMeasures.join("；");
    }
    return controlMeasures || "";
  };

  // 将字符串转换为controlMeasures数组
  const getControlMeasuresArray = (controlMeasuresString) => {
    if (!controlMeasuresString || controlMeasuresString.trim() === "") {
      return [];
    }
    return controlMeasuresString
      .split(/[；;，,\n]/)
      .filter((item) => item.trim() !== "")
      .map((item) => item.trim());
  };

  const loadAvailableRisks = useCallback(async () => {
    try {
      setLoadingRisks(true);
      const risks = await SafetyRiskPointAPI.getList();
      setAvailableRisks(Array.isArray(risks.data) ? risks.data : []);
    } catch (error) {
      console.error("加载风险点失败:", error);
      toast({
        variant: "destructive",
        title: "加载失败",
        description: "无法加载知识库中的风险点数据",
      });
      setAvailableRisks([]);
    } finally {
      setLoadingRisks(false);
    }
  }, [toast]);

  useEffect(() => {
    loadAvailableRisks();
  }, [loadAvailableRisks]);

  const handleAddRisk = () => {
    const newRisk = {
      id: `manual-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`,
      primaryTask: "",
      secondaryTask: "",
      tertiaryTask: "",
      riskName: "",
      riskType: "",
      consequence: 2,
      exposure: 2,
      likelihood: 2,
      riskValue: 8,
      riskLevel: "低风险",
      controlMeasures: [],
      source: "手动添加",
    };

    const updatedItems = [...riskItems, newRisk];
    onUpdate({ riskControlItems: updatedItems });
    setEditingRowId(newRisk.id);
  };

  const handleUpdateRisk = (riskId, field, value) => {
    const updatedItems = riskItems.map((item) => {
      if (item.id === riskId) {
        const updated = { ...item, [field]: value };
        if (field === "controlMeasures") {
          updated.controlMeasures = getControlMeasuresArray(value);
        }

        // 自动计算风险值和等级
        if (["consequence", "exposure", "likelihood"].includes(field)) {
          const c =
            field === "consequence"
              ? parseFloat(value) || 1
              : updated.consequence || 1;
          const e =
            field === "exposure"
              ? parseFloat(value) || 1
              : updated.exposure || 1;
          const l =
            field === "likelihood"
              ? parseFloat(value) || 1
              : updated.likelihood || 1;

          updated.riskValue = c * e * l;

          // 根据风险值确定风险等级
          if (updated.riskValue >= 320) {
            updated.riskLevel = "极高风险";
          } else if (updated.riskValue >= 160) {
            updated.riskLevel = "高风险";
          } else if (updated.riskValue >= 70) {
            updated.riskLevel = "中等风险";
          } else if (updated.riskValue >= 20) {
            updated.riskLevel = "低风险";
          } else {
            updated.riskLevel = "可忽略";
          }
        }

        return updated;
      }
      return item;
    });
    onUpdate({ riskControlItems: updatedItems });
  };

  const handleDeleteRisk = (riskId) => {
    const updatedItems = riskItems.filter((item) => item.id !== riskId);
    onUpdate({ riskControlItems: updatedItems });
  };

  const handleImportRisks = (importedRisks) => {
    const processedRisks = importedRisks.map((risk) => {
      const c = risk.baseConsequence || 1;
      const e = risk.baseExposure || 1;
      const l = risk.baseLikelihood || 1;
      const riskValue = c * e * l;
      let riskLevel = "可忽略";
      if (riskValue >= 320) riskLevel = "极高风险";
      else if (riskValue >= 160) riskLevel = "高风险";
      else if (riskValue >= 70) riskLevel = "中等风险";
      else if (riskValue >= 20) riskLevel = "低风险";

      return {
        id: `imported-${risk.id}-${Date.now()}-${Math.random()
          .toString(36)
          .substring(2, 9)}`,
        primaryTask: risk.primaryCategory || "",
        secondaryTask: risk.secondaryCategory || "",
        tertiaryTask: risk.tertiaryCategory || "",
        riskName: risk.riskName || risk.riskDescription || "",
        riskType: Array.isArray(risk.riskType)
          ? risk.riskType.join("、")
          : risk.riskType || "",
        consequence: c,
        exposure: e,
        likelihood: l,
        riskValue: riskValue,
        riskLevel: riskLevel,
        controlMeasures: Array.isArray(risk.controlMeasures)
          ? risk.controlMeasures
          : risk.controlMeasures
          ? [risk.controlMeasures]
          : [],
        source: "知识库",
      };
    });

    const existingRiskNames = new Set(riskItems.map((item) => item.riskName));
    const uniqueNewItems = processedRisks.filter(
      (item) => !existingRiskNames.has(item.riskName)
    );

    if (uniqueNewItems.length > 0) {
      const updatedItems = [...riskItems, ...uniqueNewItems];
      onUpdate({ riskControlItems: updatedItems });
      toast({
        title: "导入成功",
        description: `已成功导入 ${uniqueNewItems.length} 个风险点。`,
      });
    } else {
      toast({
        title: "ℹ️ 无新风险导入",
        description: "您选择的风险点均已存在，未添加任何新项目。",
      });
    }
  };

  // 智能推荐危险点
  const handleDangerous = useCallback(async () => {
    if (isAnalyzing || !scheme.id) return;
    
    try {
      setIsAnalyzing(true);
      toast({
        title: "智能推荐中",
        description: "系统正在分析并推荐相关风险点，请稍候...",
      });
      
      // 调用API获取推荐的风险点
      const response = await RecommendationsAPI.chooseSafetyRisk(scheme.id);
      
      if (response?.data && Array.isArray(response.data)) {
        const recommendedRisks = response.data;
        
        // 处理推荐的风险点，与现有风险点去重
        const existingRiskNames = new Set(riskItems.map(item => item.riskName));
        const newRisks = recommendedRisks.filter(
          risk => !existingRiskNames.has(risk.riskName)
        );
        
        if (newRisks.length > 0) {
          // 格式化风险点数据
          const formattedRisks = newRisks.map(risk => {
            const c = risk.consequence || 2;
            const e = risk.exposure || 2;
            const l = risk.likelihood || 2;
            const riskValue = c * e * l;
            let riskLevel = "低风险";
            
            if (riskValue >= 320) riskLevel = "极高风险";
            else if (riskValue >= 160) riskLevel = "高风险";
            else if (riskValue >= 70) riskLevel = "中等风险";
            else if (riskValue >= 20) riskLevel = "低风险";
            else riskLevel = "可忽略";
            
            return {
              id: `ai-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`,
              primaryTask: risk.primaryCategory || "",
              secondaryTask: risk.secondaryCategory || "",
              tertiaryTask: risk.tertiaryCategory || "",
              riskName: risk.riskName || "未命名风险",
              riskType: Array.isArray(risk.riskType) 
                ? risk.riskType.join("、") 
                : risk.riskType || "",
              consequence: c,
              exposure: e,
              likelihood: l,
              riskValue: riskValue,
              riskLevel: riskLevel,
              controlMeasures: Array.isArray(risk.controlMeasures)
                ? risk.controlMeasures
                : risk.controlMeasures ? [risk.controlMeasures] : [],
              source: "智能推荐",
            };
          });
          
          // 添加到现有风险点中
          const updatedItems = [...riskItems, ...formattedRisks];
          onUpdate({ riskControlItems: updatedItems });
          
          toast({
            title: "推荐成功",
            description: `已为您推荐 ${formattedRisks.length} 个相关风险点`,
          });
        } else {
          toast({
            title: "没有新推荐",
            description: "未找到新的相关风险点，您已添加了所有推荐项",
          });
        }
      } else {
        toast({
          title: "推荐结果为空",
          description: "未找到与当前方案相关的风险点",
        });
      }
    } catch (error) {
      console.error("获取智能推荐风险点失败:", error);
      toast({
        variant: "destructive",
        title: "推荐失败",
        description: "无法获取推荐的风险点，请稍后重试",
      });
    } finally {
      setIsAnalyzing(false);
    }
  }, [isAnalyzing, scheme.id, riskItems, onUpdate, toast]);

  const getRiskLevelColor = (level) => {
    const colors = {
      可忽略: "bg-gray-100 text-gray-800",
      低风险: "bg-green-100 text-green-800",
      中等风险: "bg-yellow-100 text-yellow-800",
      高风险: "bg-red-100 text-red-800",
      极高风险: "bg-red-200 text-red-900 font-bold",
    };
    return colors[level] || colors["低风险"];
  };

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h3 className="text-lg font-semibold flex items-center gap-2">
            <Shield className="w-5 h-5 text-red-600" />
            风险辨识与控制措施
          </h3>
          <p className="text-sm text-gray-600 mt-1">
            识别施工过程中的安全风险，制定针对性的控制措施
          </p>
        </div>

        <div className="flex gap-2">
          <Button
            size="sm"
            className="text-white bg-purple-600 hover:bg-purple-700 text-white"
            onClick={handleDangerous}
            disabled={isAnalyzing}
          >
            {isAnalyzing ? (
              <Loader2 className="w-4 h-4 mr-2 animate-spin" />
            ) : (
              <Sparkles className="w-4 h-4 mr-2" />
            )}
            智能推荐
          </Button>
          <Button
            onClick={() => setShowImportModal(true)}
            variant="outline"
            size="sm"
            disabled={loadingRisks}
          >
            {loadingRisks ? (
              <Loader2 className="w-4 h-4 mr-2 animate-spin" />
            ) : (
              <BookOpen className="w-4 h-4 mr-2" />
            )}
            从知识库导入
          </Button>
          <Button
            onClick={handleAddRisk}
            size="sm"
            className="bg-red-600 hover:bg-red-700 text-white"
          >
            <Plus className="w-4 h-4 mr-2" />
            添加风险辨识项
          </Button>
        </div>
      </div>

      {riskItems.length === 0 ? (
        <Card className="border-2 border-dashed border-gray-300">
          <CardContent className="text-center py-12">
            <Shield className="w-12 h-12 text-gray-400 mx-auto mb-4" />
            <h3 className="text-lg font-semibold text-gray-900 mb-2">
              暂无风险辨识
            </h3>
            <p className="text-gray-500 mb-4">
              请添加施工过程中可能遇到的安全风险及其控制措施
            </p>
            <div className="flex gap-2 justify-center">
              <Button
                onClick={() => setShowImportModal(true)}
                variant="outline"
                disabled={loadingRisks}
              >
                {loadingRisks ? (
                  <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                ) : (
                  <BookOpen className="w-4 h-4 mr-2" />
                )}
                从知识库导入
              </Button>
              <Button onClick={handleAddRisk}>
                <Plus className="w-4 h-4 mr-2" />
                手动添加
              </Button>
            </div>
          </CardContent>
        </Card>
      ) : (
        <Card>
          <CardContent className="p-0">
            <div className="overflow-x-auto">
              <Table>
                <TableHeader>
                  <TableRow className="bg-gray-50">
                    <TableHead className="w-12 text-center font-semibold">
                      序号
                    </TableHead>
                    <TableHead className="min-w-24 font-semibold">
                      一级任务
                    </TableHead>
                    <TableHead className="min-w-24 font-semibold">
                      二级任务
                    </TableHead>
                    <TableHead className="min-w-24 font-semibold">
                      三级任务
                    </TableHead>
                    <TableHead className="min-w-32 font-semibold">
                      风险名称
                    </TableHead>
                    <TableHead className="min-w-24 font-semibold">
                      风险种类
                    </TableHead>
                    <TableHead className="w-16 text-center font-semibold">
                      后果(C)
                    </TableHead>
                    <TableHead className="w-16 text-center font-semibold">
                      暴露(E)
                    </TableHead>
                    <TableHead className="w-16 text-center font-semibold">
                      可能性(L)
                    </TableHead>
                    <TableHead className="w-16 text-center font-semibold">
                      风险值
                    </TableHead>
                    <TableHead className="w-20 text-center font-semibold">
                      风险等级
                    </TableHead>
                    <TableHead className="min-w-48 font-semibold">
                      控制措施
                    </TableHead>
                    <TableHead className="w-16 text-center font-semibold">
                      来源
                    </TableHead>
                    <TableHead className="w-20 text-center font-semibold">
                      操作
                    </TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {riskItems.map((risk, index) => (
                    <TableRow key={risk.id} className="hover:bg-gray-50">
                      <TableCell className="text-center font-medium text-gray-600">
                        {index + 1}
                      </TableCell>

                      <TableCell>
                        {editingRowId === risk.id ? (
                          <Select
                            value={risk.primaryTask || ""}
                            onValueChange={(value) =>
                              handleUpdateRisk(risk.id, "primaryTask", value)
                            }
                          >
                            <SelectTrigger className="w-full">
                              <SelectValue placeholder="选择一级任务" />
                            </SelectTrigger>
                            <SelectContent>
                              {primaryTaskOptions.map((option) => (
                                <SelectItem
                                  key={option.value}
                                  value={option.value}
                                >
                                  {option.label}
                                </SelectItem>
                              ))}
                            </SelectContent>
                          </Select>
                        ) : (
                          <span className="text-sm">
                            {getPrimaryTaskLabel(risk.primaryTask)}
                          </span>
                        )}
                      </TableCell>
                      
                      <TableCell>
                        {editingRowId === risk.id ? (
                          <Input
                            value={risk.secondaryTask || ""}
                            onChange={(e) =>
                              handleUpdateRisk(
                                risk.id,
                                "secondaryTask",
                                e.target.value
                              )
                            }
                            placeholder="二级任务"
                            className="w-full text-sm"
                          />
                        ) : (
                          <span className="text-sm">
                            {risk.secondaryTask || "-"}
                          </span>
                        )}
                      </TableCell>
                      
                      <TableCell>
                        {editingRowId === risk.id ? (
                          <Input
                            value={risk.tertiaryTask || ""}
                            onChange={(e) =>
                              handleUpdateRisk(
                                risk.id,
                                "tertiaryTask",
                                e.target.value
                              )
                            }
                            placeholder="三级任务"
                            className="w-full text-sm"
                          />
                        ) : (
                          <span className="text-sm">
                            {risk.tertiaryTask || "-"}
                          </span>
                        )}
                      </TableCell>
                      
                      <TableCell>
                        {editingRowId === risk.id ? (
                          <Input
                            value={risk.riskName || ""}
                            onChange={(e) =>
                              handleUpdateRisk(
                                risk.id,
                                "riskName",
                                e.target.value
                              )
                            }
                            placeholder="风险名称"
                            className="w-full text-sm"
                          />
                        ) : (
                          <span className="text-sm font-medium">
                            {risk.riskName || "-"}
                          </span>
                        )}
                      </TableCell>
                      
                      <TableCell>
                        {editingRowId === risk.id ? (
                          <Input
                            value={risk.riskType || ""}
                            onChange={(e) =>
                              handleUpdateRisk(
                                risk.id,
                                "riskType",
                                e.target.value
                              )
                            }
                            placeholder="风险种类"
                            className="w-full text-sm"
                          />
                        ) : (
                          <div className="flex flex-wrap gap-1">
                            {risk.riskType
                              ?.split("、")
                              .filter(Boolean)
                              .map((typeKey) => {
                                const riskType = riskTypeS.find(
                                  (item) => item.key === typeKey
                                );
                                const displayText = riskType?.label || typeKey;
                                return (
                                  <Badge
                                    key={typeKey}
                                    variant="secondary"
                                    className="text-xs"
                                  >
                                    {displayText}
                                  </Badge>
                                );
                              })}
                            {!risk.riskType && (
                              <span className="text-sm text-gray-500">-</span>
                            )}
                          </div>
                        )}
                      </TableCell>
                      
                      <TableCell className="text-center">
                        {editingRowId === risk.id ? (
                          <Input
                            type="number"
                            min="1"
                            max="10"
                            value={risk.consequence || 1}
                            onChange={(e) =>
                              handleUpdateRisk(
                                risk.id,
                                "consequence",
                                e.target.value
                              )
                            }
                            className="w-12 text-center text-sm"
                          />
                        ) : (
                          <span className="font-medium">
                            {risk.consequence || 1}
                          </span>
                        )}
                      </TableCell>
                      
                      <TableCell className="text-center">
                        {editingRowId === risk.id ? (
                          <Input
                            type="number"
                            min="1"
                            max="10"
                            value={risk.exposure || 1}
                            onChange={(e) =>
                              handleUpdateRisk(
                                risk.id,
                                "exposure",
                                e.target.value
                              )
                            }
                            className="w-12 text-center text-sm"
                          />
                        ) : (
                          <span className="font-medium">
                            {risk.exposure || 1}
                          </span>
                        )}
                      </TableCell>
                      
                      <TableCell className="text-center">
                        {editingRowId === risk.id ? (
                          <Input
                            type="number"
                            min="1"
                            max="10"
                            value={risk.likelihood || 1}
                            onChange={(e) =>
                              handleUpdateRisk(
                                risk.id,
                                "likelihood",
                                e.target.value
                              )
                            }
                            className="w-12 text-center text-sm"
                          />
                        ) : (
                          <span className="font-medium">
                            {risk.likelihood || 1}
                          </span>
                        )}
                      </TableCell>
                      
                      <TableCell className="text-center">
                        <span className="font-bold text-blue-600">
                          {risk.riskValue || 1}
                        </span>
                      </TableCell>
                      
                      <TableCell className="text-center">
                        <Badge
                          className={getRiskLevelColor(risk.riskLevel)}
                          variant="secondary"
                        >
                          {risk.riskLevel || "低风险"}
                        </Badge>
                      </TableCell>
                      
                      <TableCell>
                        {editingRowId === risk.id ? (
                          <Textarea
                            value={getControlMeasuresDisplay(
                              risk.controlMeasures
                            )}
                            onChange={(e) =>
                              handleUpdateRisk(
                                risk.id,
                                "controlMeasures",
                                e.target.value
                              )
                            }
                            placeholder="输入控制措施，多个措施请用分号分隔..."
                            rows={2}
                            className="w-full text-sm"
                          />
                        ) : (
                          <div className="max-w-xs">
                            <span
                              className="text-sm text-gray-700"
                              title={getControlMeasuresDisplay(
                                risk.controlMeasures
                              )}
                            >
                              {(() => {
                                const displayText = getControlMeasuresDisplay(
                                  risk.controlMeasures
                                );
                                return displayText
                                  ? displayText.length > 50
                                    ? `${displayText.substring(0, 50)}...`
                                    : displayText
                                  : "-";
                              })()}
                            </span>
                          </div>
                        )}
                      </TableCell>
                      
                      <TableCell className="text-center">
                        <Badge variant="outline" className="text-xs">
                          {risk.source || "手动"}
                        </Badge>
                      </TableCell>
                      
                      <TableCell>
                        <div className="flex gap-1 justify-center">
                          {editingRowId === risk.id ? (
                            <Button
                              size="sm"
                              variant="outline"
                              onClick={() => setEditingRowId(null)}
                              className="h-7 w-7 p-0"
                              title="保存"
                            >
                              <Check className="w-3 h-3" />
                            </Button>
                          ) : (
                            <Button
                              size="sm"
                              variant="outline"
                              onClick={() => setEditingRowId(risk.id)}
                              className="h-7 w-7 p-0"
                              title="编辑"
                            >
                              <Edit3 className="w-3 h-3" />
                            </Button>
                          )}
                          <Button
                            size="sm"
                            variant="outline"
                            onClick={() => handleDeleteRisk(risk.id)}
                            className="h-7 w-7 p-0 text-red-600 hover:text-red-800"
                            title="删除"
                          >
                            <Trash2 className="w-3 h-3" />
                          </Button>
                        </div>
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          </CardContent>
        </Card>
      )}

      <RiskImportModal
        isOpen={showImportModal}
        onClose={() => setShowImportModal(false)}
        onImport={handleImportRisks}
        availableRisks={availableRisks}
      />
    </div>
  );
}

// 方案级综合措施管理器
function SchemeLevelMeasuresManager({ scheme, onUpdate }) {
  const handleMeasureUpdate = useCallback(
    (measureType, measures) => {
      onUpdate({ [measureType]: measures });
    },
    [onUpdate]
  );

  return (
    <div className="space-y-6">
      <Alert>
        <Info className="h-4 w-4" />
        <AlertTitle>方案级措施说明</AlertTitle>
        <AlertDescription>
          方案级措施适用于整个施工方案的各个环节，是贯穿始终的总体性要求和保障措施。
        </AlertDescription>
      </Alert>

      <div className="space-y-6">
        <SchemeLevelMeasuresEditor
          title="安全文明施工措施"
          measures={scheme.schemeLevelSafetyMeasures}
          onUpdate={(measures) =>
            handleMeasureUpdate("schemeLevelSafetyMeasures", measures)
          }
          icon={Shield}
          placeholder="添加整个施工过程中的安全文明施工要求"
        />

        <SchemeLevelMeasuresEditor
          title="技术保障措施"
          measures={scheme.schemeLevelTechnicalMeasures}
          onUpdate={(measures) =>
            handleMeasureUpdate("schemeLevelTechnicalMeasures", measures)
          }
          icon={Wrench}
          placeholder="添加技术方面的总体保障措施"
        />

        <SchemeLevelMeasuresEditor
          title="质量保证措施"
          measures={scheme.schemeLevelQualityMeasures}
          onUpdate={(measures) =>
            handleMeasureUpdate("schemeLevelQualityMeasures", measures)
          }
          icon={CheckSquare}
          placeholder="添加质量管理和控制方面的措施"
        />

        <SchemeLevelMeasuresEditor
          title="环境保护措施"
          measures={scheme.schemeLevelEnvironmentalMeasures}
          onUpdate={(measures) =>
            handleMeasureUpdate("schemeLevelEnvironmentalMeasures", measures)
          }
          icon={Leaf}
          placeholder="添加环境保护和污染防治措施"
        />
      </div>

      <WeatherAnalysisEditor scheme={scheme} onUpdate={onUpdate} />
    </div>
  );
}

// 带电作业措施组件
const LiveWorkMeasuresEditor = ({ scheme, onUpdate }) => {
  const currentMeasures = scheme.liveWorkMeasures || {};

  const handleFieldUpdate = (fieldName, value) => {
    const updatedMeasures = {
      ...currentMeasures,
      [fieldName]: value,
    };
    onUpdate({ liveWorkMeasures: updatedMeasures });
  };

  const handleNumberFieldUpdate = (fieldName, value) => {
    const processedValue = value === "" ? null : parseFloat(value);
    handleFieldUpdate(fieldName, processedValue);
  };

  return (
    <div className="space-y-4">
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <div>
          <Label>作业电压等级</Label>
          <Select
            value={currentMeasures.liveWorkVoltageLevel || ""}
            onValueChange={(value) =>
              handleFieldUpdate("liveWorkVoltageLevel", value)
            }
          >
            <SelectTrigger>
              <SelectValue placeholder="选择电压等级" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="10kV">10kV</SelectItem>
              <SelectItem value="35kV">35kV</SelectItem>
              <SelectItem value="110kV">110kV</SelectItem>
              <SelectItem value="220kV">220kV</SelectItem>
              <SelectItem value="500kV">500kV</SelectItem>
            </SelectContent>
          </Select>
        </div>

        <div>
          <Label>安全距离要求 (m)</Label>
          <Input
            type="number"
            step="0.1"
            value={currentMeasures.liveWorkSafetyDistance || ""}
            onChange={(e) =>
              handleNumberFieldUpdate("liveWorkSafetyDistance", e.target.value)
            }
            placeholder="例如：3.0"
          />
        </div>

        <div>
          <Label>联系单位</Label>
          <Input
            value={currentMeasures.liveWorkContactUnit || ""}
            onChange={(e) =>
              handleFieldUpdate("liveWorkContactUnit", e.target.value)
            }
            placeholder="如：运检部门、调度中心"
          />
        </div>

        <div>
          <Label>作业负责人 (可选)</Label>
          <Input
            value={currentMeasures.liveWorkSupervisor || ""}
            onChange={(e) =>
              handleFieldUpdate("liveWorkSupervisor", e.target.value)
            }
            placeholder="输入负责人姓名"
          />
        </div>

        <div>
          <Label>联系电话 (可选)</Label>
          <Input
            value={currentMeasures.liveWorkContactPhone || ""}
            onChange={(e) =>
              handleFieldUpdate("liveWorkContactPhone", e.target.value)
            }
            placeholder="联系电话（固定电话需加区号）"
          />
        </div>
      </div>

      <div>
        <Label>专用工器具清单</Label>
        <Textarea
          value={currentMeasures.liveWorkTools || ""}
          onChange={(e) => handleFieldUpdate("liveWorkTools", e.target.value)}
          placeholder="列出所需的专用工器具，如：1. 绝缘操作杆（10kV）；2. 验电器（220kV）；3. 绝缘手套（Class 00）..."
          rows={3}
        />
      </div>

      <div>
        <Label>详细安全措施</Label>
        <Textarea
          value={currentMeasures.liveWorkSafetyMeasures || ""}
          onChange={(e) =>
            handleFieldUpdate("liveWorkSafetyMeasures", e.target.value)
          }
          placeholder="详细描述带电作业的安全措施，如：1. 作业前必须检测绝缘工具绝缘性能；2. 设专职监护人，严禁监护人离开作业现场；3. 作业人员必须穿绝缘服、戴绝缘帽..."
          rows={4}
        />
      </div>
    </div>
  );
};

// 停电作业措施
const PowerOutageMeasuresEditor = ({ scheme, onUpdate, crossingPoint }) => {
  const generateUniqueId = () =>
    `item-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;

  // 优化深比较函数，避免无限循环
  const deepEqual = useMemo(() => {
    return (obj1, obj2) => {
      if (obj1 === obj2) return true;
      
      if (
        typeof obj1 !== 'object' || obj1 === null ||
        typeof obj2 !== 'object' || obj2 === null
      ) {
        return false;
      }
      
      const keys1 = Object.keys(obj1);
      const keys2 = Object.keys(obj2);
      
      if (keys1.length !== keys2.length) return false;
      
      for (const key of keys1) {
        if (!keys2.includes(key) || !deepEqual(obj1[key], obj2[key])) {
          return false;
        }
      }
      
      return true;
    };
  }, []);

  const getRobustDetailsStructure = (details) => {
    const defaults = {
      workLocationTask: { location: "", task: "" },
      powerOffDevicesName: "",
      plannedOutageStartTime: "",
      plannedOutageEndTime: "",
      dispatchSafetyMeasures: {
        requiredDisconnections: [],
        requiredPowerSwitching: [],
        requiredGroundingDevices: [],
        requiredBarriersSigns: "",
        liveEquipmentPrecautions: "",
      },
      crewInstalledGroundingWires: [],
    };

    if (!details) {
      return defaults;
    }

    const merged = { ...defaults, ...details };
    merged.workLocationTask = {
      ...defaults.workLocationTask,
      ...(details.workLocationTask || {}),
    };
    merged.dispatchSafetyMeasures = {
      ...defaults.dispatchSafetyMeasures,
      ...(details.dispatchSafetyMeasures || {}),
    };

    merged.dispatchSafetyMeasures.requiredDisconnections =
      merged.dispatchSafetyMeasures.requiredDisconnections || [];
    merged.dispatchSafetyMeasures.requiredPowerSwitching =
      merged.dispatchSafetyMeasures.requiredPowerSwitching || [];
    merged.dispatchSafetyMeasures.requiredGroundingDevices =
      merged.dispatchSafetyMeasures.requiredGroundingDevices || [];
    merged.crewInstalledGroundingWires =
      merged.crewInstalledGroundingWires || [];

    return merged;
  };

  const applyStableIdsToArray = (incomingArr, prevArr, keysToMatch) => {
    const result = [];
    if (!incomingArr) return result;

    const prevMap = new Map();
    if (prevArr) {
      prevArr.forEach((item) => {
        const contentValues = keysToMatch.map((k) => item[k] || "");
        const contentHash = JSON.stringify(contentValues);
        prevMap.set(contentHash, item.id);
      });
    }

    incomingArr.forEach((item) => {
      const contentValues = keysToMatch.map((k) => item[k] || "");
      const contentHash = JSON.stringify(contentValues);
      const existingId = prevMap.get(contentHash);
      result.push({
        id: existingId || generateUniqueId(),
        ...item,
      });
    });
    return result;
  };

  const ensureUniqueAndStableIds = useCallback((incomingDetails, prevDetails) => {
    const robustIncomingDetails = getRobustDetailsStructure(incomingDetails);
    const newDetails = { ...robustIncomingDetails };

    newDetails.dispatchSafetyMeasures = {
      ...newDetails.dispatchSafetyMeasures,
    };
    newDetails.dispatchSafetyMeasures.requiredDisconnections =
      applyStableIdsToArray(
        robustIncomingDetails.dispatchSafetyMeasures.requiredDisconnections,
        prevDetails?.dispatchSafetyMeasures?.requiredDisconnections,
        ["deviceName", "operationDetail", "remark"]
      );
    newDetails.dispatchSafetyMeasures.requiredPowerSwitching =
      applyStableIdsToArray(
        robustIncomingDetails.dispatchSafetyMeasures.requiredPowerSwitching,
        prevDetails?.dispatchSafetyMeasures?.requiredPowerSwitching,
        ["deviceName", "circuitDetail", "operationDetail"]
      );
    newDetails.dispatchSafetyMeasures.requiredGroundingDevices =
      applyStableIdsToArray(
        robustIncomingDetails.dispatchSafetyMeasures.requiredGroundingDevices,
        prevDetails?.dispatchSafetyMeasures?.requiredGroundingDevices,
        ["location", "specQuantity"]
      );

    newDetails.crewInstalledGroundingWires = applyStableIdsToArray(
      robustIncomingDetails.crewInstalledGroundingWires,
      prevDetails?.crewInstalledGroundingWires,
      ["deviceLineName", "groundingId"]
    );

    return newDetails;
  }, [getRobustDetailsStructure, applyStableIdsToArray]);

  const [powerOutageDetails, setPowerOutageDetails] = useState(
    () => ensureUniqueAndStableIds(scheme.powerOutageDetails, null)
  );

  // 优化依赖和比较逻辑，防止无限更新
  useEffect(() => {
    setPowerOutageDetails((prevDetails) => {
      const normalizedIncomingDetails = ensureUniqueAndStableIds(
        scheme.powerOutageDetails,
        prevDetails
      );

      if (!deepEqual(prevDetails, normalizedIncomingDetails)) {
        return normalizedIncomingDetails;
      }
      return prevDetails;
    });
  }, [scheme.powerOutageDetails, ensureUniqueAndStableIds, deepEqual]);

  const handleUpdate = (field, value) => {
    const updatedDetails = { ...powerOutageDetails, [field]: value };
    setPowerOutageDetails(updatedDetails);
    onUpdate({ powerOutageDetails: updatedDetails });
  };

  const handleNestedUpdate = (parentField, childField, value) => {
    const updatedParent = {
      ...powerOutageDetails[parentField],
      [childField]: value,
    };
    handleUpdate(parentField, updatedParent);
  };

  const handleAddNestedArrayItem = (
    parentField,
    childField,
    newItemTemplate
  ) => {
    const updatedParent = { ...powerOutageDetails[parentField] };
    updatedParent[childField] = [
      ...(updatedParent[childField] || []),
      { id: generateUniqueId(), ...newItemTemplate },
    ];
    handleUpdate(parentField, updatedParent);
  };

  const handleRemoveNestedArrayItem = (parentField, childField, itemId) => {
    const updatedParent = { ...powerOutageDetails[parentField] };
    updatedParent[childField] = (updatedParent[childField] || []).filter(
      (item) => item.id !== itemId
    );
    handleUpdate(parentField, updatedParent);
  };

  const handleUpdateNestedArrayItem = (
    parentField,
    childField,
    itemId,
    newProps
  ) => {
    const updatedParent = { ...powerOutageDetails[parentField] };
    updatedParent[childField] = (updatedParent[childField] || []).map((item) =>
      item.id === itemId ? { ...item, ...newProps } : item
    );
    handleUpdate(parentField, updatedParent);
  };

  const handleAddGroundingWire = (newItemTemplate) => {
    const updatedArray = [
      ...(powerOutageDetails.crewInstalledGroundingWires || []),
      { id: generateUniqueId(), ...newItemTemplate },
    ];
    handleUpdate("crewInstalledGroundingWires", updatedArray);
  };

  const handleRemoveGroundingWire = (itemId) => {
    const updatedArray = (
      powerOutageDetails.crewInstalledGroundingWires || []
    ).filter((item) => item.id !== itemId);
    handleUpdate("crewInstalledGroundingWires", updatedArray);
  };

  const handleUpdateGroundingWire = (itemId, newProps) => {
    const updatedArray = (
      powerOutageDetails.crewInstalledGroundingWires || []
    ).map((item) => (item.id === itemId ? { ...item, ...newProps } : item));
    handleUpdate("crewInstalledGroundingWires", updatedArray);
  };

  const formatDateTimeLocal = (isoString) => {
    if (!isoString) return "";
    const date = new Date(isoString);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, "0");
    const day = String(date.getDate()).padStart(2, "0");
    const hours = String(date.getHours()).padStart(2, "0");
    const minutes = String(date.getMinutes()).padStart(2, "0");
    return `${year}-${month}-${day}T${hours}:${minutes}`;
  };

  const handleDateTimeChange = (field, value) => {
    const isoString = value ? new Date(value).toISOString() : "";
    handleUpdate(field, isoString);
  };

  const handleAutoFill = () => {
    let autoLocation = "";
    let autoTask = "";
    let autoDeviceName = "";

    if (crossingPoint) {
      autoLocation = `${crossingPoint.crossingObject || ""}${
        crossingPoint.crossingPosition
          ? " " + crossingPoint.crossingPosition
          : ""
      }`.trim();

      autoTask = `${crossingPoint.name || ""}${
        scheme.name ? " " + scheme.name : ""
      }`.trim();

      autoDeviceName = autoLocation || crossingPoint.crossingObject || "";
    }

    const currentDetailsSafe = getRobustDetailsStructure(powerOutageDetails);

    const appendOrSet = (currentValue, newValue) => {
      if (!newValue) return currentValue;
      if (!currentValue) return newValue;
      const trimmedNewValue = newValue.trim();
      if (currentValue.includes(trimmedNewValue)) return currentValue;
      return `${currentValue.trim()}\n${trimmedNewValue}`.trim();
    };

    const newLocation = appendOrSet(
      currentDetailsSafe.workLocationTask?.location,
      autoLocation
    );
    const newTask = appendOrSet(
      currentDetailsSafe.workLocationTask?.task,
      autoTask
    );
    const newPowerOffDevicesName = appendOrSet(
      currentDetailsSafe.powerOffDevicesName,
      autoDeviceName
    );

    const newPlannedStart = scheme.constructionStartDate
      ? new Date(`${scheme.constructionStartDate}T08:00:00`).toISOString()
      : currentDetailsSafe.plannedOutageStartTime;

    const newPlannedEnd = scheme.constructionEndDate
      ? new Date(`${scheme.constructionEndDate}T18:00:00`).toISOString()
      : currentDetailsSafe.plannedOutageEndTime;

    const updatedDetails = {
      ...currentDetailsSafe,
      workLocationTask: {
        ...currentDetailsSafe.workLocationTask,
        location: newLocation,
        task: newTask,
      },
      powerOffDevicesName: newPowerOffDevicesName,
      plannedOutageStartTime: newPlannedStart,
      plannedOutageEndTime: newPlannedEnd,
    };

    setPowerOutageDetails(updatedDetails);
    onUpdate("powerOutageDetails", updatedDetails);
  };

  return (
    <div className="space-y-6">
      {/* 工作地点及任务 */}
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <CardTitle className="text-lg flex items-center gap-2">
              <MapPin className="w-5 h-5 text-blue-600" />
              工作地点及任务
            </CardTitle>
          </div>
        </CardHeader>
        <CardContent className="space-y-4">
          <div>
            <Label htmlFor="work-location">工作地点或设备</Label>
            <Textarea
              id="work-location"
              placeholder="注明变（配）电站、线路名称、设备双重名称及起止杆号"
              value={powerOutageDetails.workLocationTask?.location || ""}
              onChange={(e) =>
                handleNestedUpdate(
                  "workLocationTask",
                  "location",
                  e.target.value
                )
              }
              rows={3}
            />
          </div>

          <div>
            <Label htmlFor="work-task">工作任务</Label>
            <Textarea
              id="work-task"
              placeholder="详细描述工作任务内容"
              value={powerOutageDetails.workLocationTask?.task || ""}
              onChange={(e) =>
                handleNestedUpdate("workLocationTask", "task", e.target.value)
              }
              rows={3}
            />
          </div>

          <div>
            <Label htmlFor="power-off-devices">停电设备或线路名称</Label>
            <Input
              id="power-off-devices"
              placeholder="如：10kV 横沥 F15 新兴线 73T1 开关后段线路"
              value={powerOutageDetails.powerOffDevicesName || ""}
              onChange={(e) =>
                handleUpdate("powerOffDevicesName", e.target.value)
              }
            />
          </div>

          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <div>
              <Label htmlFor="planned-start-time">计划申请停电开始时间</Label>
              <Input
                id="planned-start-time"
                type="datetime-local"
                value={formatDateTimeLocal(
                  powerOutageDetails.plannedOutageStartTime
                )}
                onChange={(e) =>
                  handleDateTimeChange("plannedOutageStartTime", e.target.value)
                }
              />
            </div>

            <div>
              <Label htmlFor="planned-end-time">计划申请停电结束时间</Label>
              <Input
                id="planned-end-time"
                type="datetime-local"
                value={formatDateTimeLocal(
                  powerOutageDetails.plannedOutageEndTime
                )}
                onChange={(e) =>
                  handleDateTimeChange("plannedOutageEndTime", e.target.value)
                }
              />
            </div>
          </div>
        </CardContent>
      </Card>

      {/* 调度或设备运维单位负责的安全措施 */}
      <Card>
        <CardHeader>
          <CardTitle className="text-lg flex items-center gap-2">
            <Shield className="w-5 h-5 text-green-600" />
            调度或设备运维单位负责的安全措施
          </CardTitle>
        </CardHeader>
        <CardContent className="space-y-6">
          {/* 应拉断路器（开关）、隔离开关（刀闸）和熔断器 */}
          <div>
            <div className="flex items-center justify-between mb-3">
              <Label className="text-base font-semibold">
                应拉断路器（开关）、隔离开关（刀闸）和熔断器
              </Label>
              <Button
                type="button"
                size="sm"
                onClick={() =>
                  handleAddNestedArrayItem(
                    "dispatchSafetyMeasures",
                    "requiredDisconnections",
                    {
                      deviceName: "",
                      operationDetail: "",
                      remark: "",
                    }
                  )
                }
              >
                <Plus className="w-4 h-4 mr-2" />
                添加设备操作
              </Button>
            </div>

            <div className="space-y-3">
              {(
                powerOutageDetails.dispatchSafetyMeasures
                  ?.requiredDisconnections || []
              ).map((item) => (
                <Card key={item.id} className="p-4">
                  <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
                    <div>
                      <Label htmlFor={`disconnect-device-${item.id}`}>
                        设备名称
                      </Label>
                      <Input
                        id={`disconnect-device-${item.id}`}
                        placeholder="如：新兴线#73杆73T1开关"
                        value={item.deviceName || ""}
                        onChange={(e) =>
                          handleUpdateNestedArrayItem(
                            "dispatchSafetyMeasures",
                            "requiredDisconnections",
                            item.id,
                            {
                              deviceName: e.target.value,
                            }
                          )
                        }
                      />
                    </div>

                    <div>
                      <Label htmlFor={`disconnect-operation-${item.id}`}>
                        操作详情
                      </Label>
                      <Input
                        id={`disconnect-operation-${item.id}`}
                        placeholder="如：断开、拉开"
                        value={item.operationDetail || ""}
                        onChange={(e) =>
                          handleUpdateNestedArrayItem(
                            "dispatchSafetyMeasures",
                            "requiredDisconnections",
                            item.id,
                            {
                              operationDetail: e.target.value,
                            }
                          )
                        }
                      />
                    </div>

                    <div className="flex items-end gap-2">
                      <div className="flex-1">
                        <Label htmlFor={`disconnect-remark-${item.id}`}>
                          备注/编号
                        </Label>
                        <Input
                          id={`disconnect-remark-${item.id}`}
                          placeholder="如：73T11刀闸"
                          value={item.remark || ""}
                          onChange={(e) =>
                            handleUpdateNestedArrayItem(
                              "dispatchSafetyMeasures",
                              "requiredDisconnections",
                              item.id,
                              {
                                remark: e.target.value,
                              }
                            )
                          }
                        />
                      </div>
                      <Button
                        type="button"
                        variant="outline"
                        size="sm"
                        onClick={() =>
                          handleRemoveNestedArrayItem(
                            "dispatchSafetyMeasures",
                            "requiredDisconnections",
                            item.id
                          )
                        }
                      >
                        <Trash2 className="w-4 h-4" />
                      </Button>
                    </div>
                  </div>
                </Card>
              ))}

              {(!powerOutageDetails.dispatchSafetyMeasures
                ?.requiredDisconnections ||
                powerOutageDetails.dispatchSafetyMeasures.requiredDisconnections
                  .length === 0) && (
                <div className="text-center py-4 text-gray-500 border border-dashed rounded-lg">
                  暂未添加断路器操作项目
                </div>
              )}
            </div>
          </div>

          {/* 应投切的相关交直流电源及二次回路 */}
          <div>
            <div className="flex items-center justify-between mb-3">
              <Label className="text-base font-semibold">
                应投切的相关交直流电源（空气开关、熔断器、连接片）及二次回路
              </Label>
              <Button
                type="button"
                size="sm"
                onClick={() =>
                  handleAddNestedArrayItem(
                    "dispatchSafetyMeasures",
                    "requiredPowerSwitching",
                    {
                      deviceName: "",
                      circuitDetail: "",
                      operationDetail: "",
                    }
                  )
                }
              >
                <Plus className="w-4 h-4 mr-2" />
                添加电源操作
              </Button>
            </div>

            <div className="space-y-3">
              {(
                powerOutageDetails.dispatchSafetyMeasures
                  ?.requiredPowerSwitching || []
              ).map((item) => (
                <Card key={item.id} className="p-4">
                  <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
                    <div>
                      <Label htmlFor={`power-device-${item.id}`}>
                        设备名称
                      </Label>
                      <Input
                        id={`power-device-${item.id}`}
                        placeholder="如：变压器4001G刀闸"
                        value={item.deviceName || ""}
                        onChange={(e) =>
                          handleUpdateNestedArrayItem(
                            "dispatchSafetyMeasures",
                            "requiredPowerSwitching",
                            item.id,
                            {
                              deviceName: e.target.value,
                            }
                          )
                        }
                      />
                    </div>

                    <div>
                      <Label htmlFor={`power-circuit-${item.id}`}>
                        回路/连接片详情
                      </Label>
                      <Input
                        id={`power-circuit-${item.id}`}
                        placeholder="如：负荷侧连接片"
                        value={item.circuitDetail || ""}
                        onChange={(e) =>
                          handleUpdateNestedArrayItem(
                            "dispatchSafetyMeasures",
                            "requiredPowerSwitching",
                            item.id,
                            {
                              circuitDetail: e.target.value,
                            }
                          )
                        }
                      />
                    </div>

                    <div className="flex items-end gap-2">
                      <div className="flex-1">
                        <Label htmlFor={`power-operation-${item.id}`}>
                          操作详情
                        </Label>
                        <Input
                          id={`power-operation-${item.id}`}
                          placeholder="如：拉开、投切"
                          value={item.operationDetail || ""}
                          onChange={(e) =>
                            handleUpdateNestedArrayItem(
                              "dispatchSafetyMeasures",
                              "requiredPowerSwitching",
                              item.id,
                              {
                                operationDetail: e.target.value,
                              }
                            )
                          }
                        />
                      </div>
                      <Button
                        type="button"
                        variant="outline"
                        size="sm"
                        onClick={() =>
                          handleRemoveNestedArrayItem(
                            "dispatchSafetyMeasures",
                            "requiredPowerSwitching",
                            item.id
                          )
                        }
                      >
                        <Trash2 className="w-4 h-4" />
                      </Button>
                    </div>
                  </div>
                </Card>
              ))}

              {(!powerOutageDetails.dispatchSafetyMeasures
                ?.requiredPowerSwitching ||
                powerOutageDetails.dispatchSafetyMeasures.requiredPowerSwitching
                  .length === 0) && (
                <div className="text-center py-4 text-gray-500 border border-dashed rounded-lg">
                  暂未添加电源投切项目
                </div>
              )}
            </div>
          </div>

          {/* 应合的接地刀闸或应装的接地线 */}
          <div>
            <div className="flex items-center justify-between mb-3">
              <Label className="text-base font-semibold">
                应合的接地刀闸（注明双重名称）或应装的接地线（装设地点）
              </Label>
              <Button
                type="button"
                size="sm"
                onClick={() =>
                  handleAddNestedArrayItem(
                    "dispatchSafetyMeasures",
                    "requiredGroundingDevices",
                    {
                      location: "",
                      specQuantity: "",
                    }
                  )
                }
              >
                <Plus className="w-4 h-4 mr-2" />
                添加接地设备
              </Button>
            </div>

            <div className="space-y-3">
              {(
                powerOutageDetails.dispatchSafetyMeasures
                  ?.requiredGroundingDevices || []
              ).map((item) => (
                <Card key={item.id} className="p-4">
                  <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                    <div>
                      <Label htmlFor={`grounding-location-${item.id}`}>
                        装设位置
                      </Label>
                      <Input
                        id={`grounding-location-${item.id}`}
                        placeholder="如：新兴线#73杆73T12刀闸架空线侧"
                        value={item.location || ""}
                        onChange={(e) =>
                          handleUpdateNestedArrayItem(
                            "dispatchSafetyMeasures",
                            "requiredGroundingDevices",
                            item.id,
                            {
                              location: e.target.value,
                            }
                          )
                        }
                      />
                    </div>

                    <div className="flex items-end gap-2">
                      <div className="flex-1">
                        <Label htmlFor={`grounding-spec-${item.id}`}>
                          规格及数量
                        </Label>
                        <Input
                          id={`grounding-spec-${item.id}`}
                          placeholder="如：装设接地线1组"
                          value={item.specQuantity || ""}
                          onChange={(e) =>
                            handleUpdateNestedArrayItem(
                              "dispatchSafetyMeasures",
                              "requiredGroundingDevices",
                              item.id,
                              {
                                specQuantity: e.target.value,
                              }
                            )
                          }
                        />
                      </div>
                      <Button
                        type="button"
                        variant="outline"
                        size="sm"
                        onClick={() =>
                          handleRemoveNestedArrayItem(
                            "dispatchSafetyMeasures",
                            "requiredGroundingDevices",
                            item.id
                          )
                        }
                      >
                        <Trash2 className="w-4 h-4" />
                      </Button>
                    </div>
                  </div>
                </Card>
              ))}

              {(!powerOutageDetails.dispatchSafetyMeasures
                ?.requiredGroundingDevices ||
                powerOutageDetails.dispatchSafetyMeasures
                  .requiredGroundingDevices.length === 0) && (
                <div className="text-center py-4 text-gray-500 border border-dashed rounded-lg">
                  暂未添加接地设备项目
                </div>
              )}
            </div>
          </div>

          {/* 应设遮栏、应挂标志牌 */}
          <div>
            <Label htmlFor="barriers-signs">
              应设遮栏、应挂标志牌（注明位置）
            </Label>
            <Textarea
              id="barriers-signs"
              placeholder="如：&#13;&#10;1.在上述已断开的开关、已拉开的刀闸操作部位或明显位置悬挂'禁止合闸，线路有人工作'标志牌；&#13;&#10;2.在工作地点四周装设围栏并悬挂'在此工作！'标志牌。"
              value={
                powerOutageDetails.dispatchSafetyMeasures
                  ?.requiredBarriersSigns || ""
              }
              onChange={(e) =>
                handleNestedUpdate(
                  "dispatchSafetyMeasures",
                  "requiredBarriersSigns",
                  e.target.value
                )
              }
              rows={4}
            />
          </div>

          {/* 保留或邻近的带电设备或线路 */}
          <div>
            <Label htmlFor="live-equipment">
              保留或邻近的带电设备或线路，及其他安全措施和注意事项
            </Label>
            <Textarea
              id="live-equipment"
              placeholder="如：10kV 横沥 F15 新兴线#73杆73T11刀闸架空线侧前段线路带电。"
              value={
                powerOutageDetails.dispatchSafetyMeasures
                  ?.liveEquipmentPrecautions || ""
              }
              onChange={(e) =>
                handleNestedUpdate(
                  "dispatchSafetyMeasures",
                  "liveEquipmentPrecautions",
                  e.target.value
                )
              }
              rows={3}
            />
          </div>
        </CardContent>
      </Card>

      {/* 工作班组自行装设的接地线 */}
      <Card>
        <CardHeader>
          <CardTitle className="text-lg flex items-center gap-2">
            <Zap className="w-5 h-5 text-yellow-600" />
            工作班组自行装设的接地线（接地刀闸）
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="flex items-center justify-between mb-3">
            <Label className="text-base font-semibold">接地线装设表</Label>
            <Button
              type="button"
              size="sm"
              onClick={() =>
                handleAddGroundingWire({
                  deviceLineName: "",
                  groundingId: "",
                })
              }
            >
              <Plus className="w-4 h-4 mr-2" />
              添加接地线
            </Button>
          </div>

          <div className="border rounded-lg overflow-hidden">
            <Table>
              <TableHeader>
                <TableRow>
                  <TableHead>设备或线路名称（杆号）</TableHead>
                  <TableHead>地刀或接地线编号</TableHead>
                  <TableHead className="w-20">操作</TableHead>
                </TableRow>
              </TableHeader>
              <TableBody>
                {(powerOutageDetails.crewInstalledGroundingWires || []).map(
                  (item) => (
                    <TableRow key={item.id}>
                      <TableCell>
                        <Input
                          placeholder="如：新兴线#14杆"
                          value={item.deviceLineName || ""}
                          onChange={(e) =>
                            handleUpdateGroundingWire(item.id, {
                              deviceLineName: e.target.value,
                            })
                          }
                        />
                      </TableCell>
                      <TableCell>
                        <Input
                          placeholder="如：JD-001"
                          value={item.groundingId || ""}
                          onChange={(e) =>
                            handleUpdateGroundingWire(item.id, {
                              groundingId: e.target.value,
                            })
                          }
                        />
                      </TableCell>
                      <TableCell>
                        <Button
                          type="button"
                          variant="outline"
                          size="sm"
                          onClick={() => handleRemoveGroundingWire(item.id)}
                        >
                          <Trash2 className="w-4 h-4" />
                        </Button>
                      </TableCell>
                    </TableRow>
                  )
                )}

                {(!powerOutageDetails.crewInstalledGroundingWires ||
                  powerOutageDetails.crewInstalledGroundingWires.length ===
                    0) && (
                  <TableRow>
                    <TableCell
                      colSpan={3}
                      className="text-center py-4 text-gray-500"
                    >
                      暂未添加工作班组接地线装设记录
                    </TableCell>
                  </TableRow>
                )}
              </TableBody>
            </Table>
          </div>
        </CardContent>
      </Card>

      {/* 兼容性：保留原有的详细措施描述字段 */}
      <Card>
        <CardHeader>
          <CardTitle className="text-lg flex items-center gap-2">
            <FileText className="w-5 h-5 text-gray-600" />
            补充说明
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div>
            <Label htmlFor="additional-measures">
              详细措施内容补充（可选）
            </Label>
            <Textarea
              id="supplement"
              placeholder="如需要补充说明，请在此处填写..."
              value={powerOutageDetails.supplement || ""}
              onChange={(e) => handleUpdate("supplement", e.target.value)}
              rows={4}
            />
          </div>
        </CardContent>
      </Card>
    </div>
  );
};

// 封路措施组件
const RoadClosureMeasuresEditor = ({ scheme, onUpdate }) => {
  const currentMeasures = scheme.roadClosureMeasures || {};

  const handleFieldUpdate = (fieldName, value) => {
    const updatedMeasures = {
      ...currentMeasures,
      [fieldName]: value,
    };
    onUpdate({ roadClosureMeasures: updatedMeasures });
  };

  const handleNumberFieldUpdate = (fieldName, value) => {
    const processedValue = value === "" ? null : parseFloat(value);
    handleFieldUpdate(fieldName, processedValue);
  };

  return (
    <div className="space-y-4">
      <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
        <div>
          <Label>封路类型</Label>
          <Select
            value={currentMeasures.roadClosureType || ""}
            onValueChange={(value) =>
              handleFieldUpdate("roadClosureType", value)
            }
          >
            <SelectTrigger>
              <SelectValue placeholder="选择封路类型" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="fullClosure">全封闭</SelectItem>
              <SelectItem value="partialClosure">部分封闭</SelectItem>
              <SelectItem value="laneControl">车道管制</SelectItem>
              <SelectItem value="timeControl">分时段管制</SelectItem>
            </SelectContent>
          </Select>
        </div>

        <div>
          <Label>封路时长 (小时)</Label>
          <Input
            type="number"
            step="0.5"
            value={currentMeasures.roadClosureDuration || ""}
            onChange={(e) =>
              handleNumberFieldUpdate("roadClosureDuration", e.target.value)
            }
            placeholder="预计封路时长"
          />
        </div>

        <div>
          <Label>联系单位</Label>
          <Input
            value={currentMeasures.roadClosurePoliceUnit || ""}
            onChange={(e) =>
              handleFieldUpdate("roadClosurePoliceUnit", e.target.value)
            }
            placeholder="如：XX市公安局交警支队"
          />
        </div>

        <div>
          <Label>交警联系人 (可选)</Label>
          <Input
            value={currentMeasures.roadClosurePoliceContact || ""}
            onChange={(e) =>
              handleFieldUpdate("roadClosurePoliceContact", e.target.value)
            }
            placeholder="交警负责人姓名"
          />
        </div>

        <div>
          <Label>交警联系电话 (可选)</Label>
          <Input
            value={currentMeasures.roadClosurePolicePhone || ""}
            onChange={(e) =>
              handleFieldUpdate("roadClosurePolicePhone", e.target.value)
            }
            placeholder="交警联系电话"
          />
        </div>

        <div>
          <Label>绕行路线</Label>
          <Input
            value={currentMeasures.roadClosureDetourRoute || ""}
            onChange={(e) =>
              handleFieldUpdate("roadClosureDetourRoute", e.target.value)
            }
            placeholder="建议绕行路线"
          />
        </div>

        <div>
          <Label>施工路段桩号</Label>
          <Input
            value={currentMeasures.roadClosureStakeNumber || ""}
            onChange={(e) =>
              handleFieldUpdate("roadClosureStakeNumber", e.target.value)
            }
            placeholder="例如：K15+200-K15+800"
          />
        </div>
      </div>

      <div>
        <Label>交通组织方案</Label>
        <Textarea
          value={currentMeasures.roadClosurePlan || ""}
          onChange={(e) => handleFieldUpdate("roadClosurePlan", e.target.value)}
          placeholder="详细描述交通组织和管制方案..."
          rows={4}
        />
      </div>

      <div>
        <Label>应急预案</Label>
        <Textarea
          value={currentMeasures.roadClosureEmergencyPlan || ""}
          onChange={(e) =>
            handleFieldUpdate("roadClosureEmergencyPlan", e.target.value)
          }
          placeholder="描述交通事故或其他紧急情况的处置措施..."
          rows={3}
        />
      </div>
    </div>
  );
};

// 交通管制措施组件
const TrafficControlMeasuresEditor = ({ scheme, onUpdate }) => {
  const currentMeasures = scheme.trafficControlMeasures || {};

  const handleFieldUpdate = (fieldName, value) => {
    const updatedMeasures = {
      ...currentMeasures,
      [fieldName]: value,
    };
    onUpdate({ trafficControlMeasures: updatedMeasures });
  };

  const handleNumberFieldUpdate = (fieldName, value) => {
    const processedValue = value === "" ? null : parseInt(value, 10);
    handleFieldUpdate(fieldName, processedValue);
  };

  return (
    <div className="space-y-4">
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div>
          <Label>铁路线路名称</Label>
          <Input
            value={currentMeasures.railwayLineName || ""}
            onChange={(e) =>
              handleFieldUpdate("railwayLineName", e.target.value)
            }
            placeholder="例如：京沪高铁、京广铁路"
          />
        </div>

        <div>
          <Label>管制类型</Label>
          <Select
            value={currentMeasures.trafficControlType || ""}
            onValueChange={(value) =>
              handleFieldUpdate("trafficControlType", value)
            }
          >
            <SelectTrigger>
              <SelectValue placeholder="选择管制类型" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="speedLimit">限速运行</SelectItem>
              <SelectItem value="temporaryStop">临时停车</SelectItem>
              <SelectItem value="routeChange">改道运行</SelectItem>
              <SelectItem value="fullStop">全线停运</SelectItem>
            </SelectContent>
          </Select>
        </div>

        <div>
          <Label>管制时间窗口</Label>
          <Input
            value={currentMeasures.trafficControlTimeWindow || ""}
            onChange={(e) =>
              handleFieldUpdate("trafficControlTimeWindow", e.target.value)
            }
            placeholder="例如：凌晨1:00-5:00、每日22:00-次日6:00"
          />
        </div>

        <div>
          <Label>限速值 (km/h)</Label>
          <Input
            type="number"
            min="0"
            value={currentMeasures.trafficControlSpeedLimit || ""}
            onChange={(e) =>
              handleNumberFieldUpdate(
                "trafficControlSpeedLimit",
                e.target.value
              )
            }
            placeholder="例如：60、80（仅管制类型为'限速运行'时填写）"
          />
        </div>

        <div>
          <Label>联系单位</Label>
          <Input
            value={currentMeasures.railwayDispatchUnit || ""}
            onChange={(e) =>
              handleFieldUpdate("railwayDispatchUnit", e.target.value)
            }
            placeholder="如：XX铁路局调度中心、XX铁路公安处"
          />
        </div>

        <div>
          <Label>铁路调度联系人 (可选)</Label>
          <Input
            value={currentMeasures.railwayDispatcherContact || ""}
            onChange={(e) =>
              handleFieldUpdate("railwayDispatcherContact", e.target.value)
            }
            placeholder="调度员姓名、负责人姓名"
          />
        </div>

        <div>
          <Label>调度室电话 (可选)</Label>
          <Input
            value={currentMeasures.railwayDispatcherPhone || ""}
            onChange={(e) =>
              handleFieldUpdate("railwayDispatcherPhone", e.target.value)
            }
            placeholder="固定电话需加区号（如：010-12345678）"
          />
        </div>
      </div>

      <div>
        <Label>防护措施</Label>
        <Textarea
          value={currentMeasures.railwayProtectionMeasures || ""}
          onChange={(e) =>
            handleFieldUpdate("railwayProtectionMeasures", e.target.value)
          }
          placeholder="描述施工防护措施，如设置防护员、通信联络等..."
          rows={3}
        />
      </div>

      <div>
        <Label>详细管制计划</Label>
        <Textarea
          value={currentMeasures.trafficControlPlan || ""}
          onChange={(e) =>
            handleFieldUpdate("trafficControlPlan", e.target.value)
          }
          placeholder="详细描述交通管制的具体安排..."
          rows={4}
        />
      </div>
    </div>
  );
};

// 停航作业措施组件
const NavigationControlMeasuresEditor = ({ scheme, onUpdate }) => {
  const currentMeasures = scheme.navigationControlMeasures || {};

  const handleFieldUpdate = (fieldName, value) => {
    const updatedMeasures = {
      ...currentMeasures,
      [fieldName]: value,
    };
    onUpdate({ navigationControlMeasures: updatedMeasures });
  };

  const handleNumberFieldUpdate = (fieldName, value) => {
    const processedValue = value === "" ? null : parseFloat(value);
    handleFieldUpdate(fieldName, processedValue);
  };

  return (
    <div className="space-y-4">
      <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
        <div>
          <Label>水域名称</Label>
          <Input
            value={currentMeasures.waterwayName || ""}
            onChange={(e) => handleFieldUpdate("waterwayName", e.target.value)}
            placeholder="例如：长江武汉段、珠江三角洲航道、太湖流域"
          />
        </div>

        <div>
          <Label>航道等级</Label>
          <Select
            value={currentMeasures.waterwayLevel || ""}
            onValueChange={(value) => handleFieldUpdate("waterwayLevel", value)}
          >
            <SelectTrigger>
              <SelectValue placeholder="选择航道等级" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="I">Ⅰ级（通航3000吨级及以上船舶）</SelectItem>
              <SelectItem value="II">Ⅱ级（通航2000吨级船舶）</SelectItem>
              <SelectItem value="III">Ⅲ级（通航1000吨级船舶）</SelectItem>
              <SelectItem value="IV">Ⅳ级（通航500吨级船舶）</SelectItem>
              <SelectItem value="V">Ⅴ级（通航300吨级船舶）</SelectItem>
              <SelectItem value="VI">Ⅵ级（通航100吨级船舶）</SelectItem>
              <SelectItem value="VII">Ⅶ级（通航50吨级及以下船舶）</SelectItem>
            </SelectContent>
          </Select>
        </div>

        <div>
          <Label>停航类型</Label>
          <Select
            value={currentMeasures.navigationControlType || ""}
            onValueChange={(value) =>
              handleFieldUpdate("navigationControlType", value)
            }
          >
            <SelectTrigger>
              <SelectValue placeholder="选择停航类型" />
            </SelectTrigger>
            <SelectContent>
              <SelectItem value="fullStop">全水域停航</SelectItem>
              <SelectItem value="partialStop">局部水域停航</SelectItem>
              <SelectItem value="timeSlotStop">分时段停航</SelectItem>
              <SelectItem value="shipTypeLimit">
                船舶类型限制（仅允许小型船舶通行）
              </SelectItem>
            </SelectContent>
          </Select>
        </div>

        <div>
          <Label>停航时长 (小时)</Label>
          <Input
            type="number"
            step="0.5"
            value={currentMeasures.navigationStopDuration || ""}
            onChange={(e) =>
              handleNumberFieldUpdate("navigationStopDuration", e.target.value)
            }
            placeholder="例如：8、12.5（分时段停航需注明每日时长）"
          />
        </div>

        <div>
          <Label>作业水域安全距离 (m)</Label>
          <Input
            type="number"
            step="0.1"
            value={currentMeasures.navigationSafetyDistance || ""}
            onChange={(e) =>
              handleNumberFieldUpdate(
                "navigationSafetyDistance",
                e.target.value
              )
            }
            placeholder="例如：50（作业区域周边50米内禁止船舶进入）"
          />
        </div>

        <div>
          <Label>海事联系单位</Label>
          <Input
            value={currentMeasures.maritimeContactUnit || ""}
            onChange={(e) =>
              handleFieldUpdate("maritimeContactUnit", e.target.value)
            }
            placeholder="如：XX海事局通航管理处、XX海事执法支队"
          />
        </div>

        <div>
          <Label>海事联系人 (可选)</Label>
          <Input
            value={currentMeasures.maritimeContactPerson || ""}
            onChange={(e) =>
              handleFieldUpdate("maritimeContactPerson", e.target.value)
            }
            placeholder="海事负责人姓名、执法人员姓名"
          />
        </div>

        <div>
          <Label>海事联系电话 (可选)</Label>
          <Input
            value={currentMeasures.maritimeContactPhone || ""}
            onChange={(e) =>
              handleFieldUpdate("maritimeContactPhone", e.target.value)
            }
            placeholder="24小时值班电话（如：021-12395）"
          />
        </div>
      </div>

      <div>
        <Label>警戒范围与标识设置</Label>
        <Textarea
          value={currentMeasures.navigationWarningSetup || ""}
          onChange={(e) =>
            handleFieldUpdate("navigationWarningSetup", e.target.value)
          }
          placeholder="描述警戒范围及标识，如：1. 在作业水域上下游1公里处设置‘前方作业，禁止通行’警示牌；2. 安排2艘警戒船在作业区域两侧巡逻；3. 夜间开启红色警示灯（频率1次/秒）..."
          rows={3}
        />
      </div>

      <div>
        <Label>船舶绕行路线指引</Label>
        <Textarea
          value={currentMeasures.navigationDetourRoute || ""}
          onChange={(e) =>
            handleFieldUpdate("navigationDetourRoute", e.target.value)
          }
          placeholder="详细说明绕行路线，如：1. 上行船舶从作业水域北侧辅航道通行（宽度80米，水深6米）；2. 下行船舶需提前2小时联系海事部门获取实时通航指令；3. 绕行路线全程设置浮标标识..."
          rows={3}
        />
      </div>

      <div>
        <Label>水上应急预案</Label>
        <Textarea
          value={currentMeasures.navigationEmergencyPlan || ""}
          onChange={(e) =>
            handleFieldUpdate("navigationEmergencyPlan", e.target.value)
          }
          placeholder="描述水上突发事件处置措施，如：1. 船舶闯入作业区时，立即停止作业并启动声光警示；2. 配备救生艇1艘、救生衣10件，应对人员落水事故；3. 与附近海事救援站建立直通电话，确保15分钟内抵达现场..."
          rows={4}
        />
      </div>
    </div>
  );
};

// 专项措施管理器组件
function SpecialMeasuresManager({ scheme, onUpdate, crossingPoint, project }) {
  const { toast } = useToast();

  const handleMeasureToggle = useCallback(
    (measureKey) => {
      const currentConfig = scheme.specialMeasuresConfig || {};
      const newConfig = {
        ...currentConfig,
        [measureKey]: !currentConfig[measureKey],
      };
      onUpdate({ specialMeasuresConfig: newConfig });
    },
    [scheme, onUpdate]
  );

  const handleLocalSchemeUpdate = useCallback(
    (updates) => {
      onUpdate(updates);
    },
    [onUpdate]
  );

  const measureOptions = useMemo(() => {
    return [
      {
        key: "liveWorkMeasures",
        label: "带电作业措施",
        description: "适用于带电跨越电力线路。",
        icon: Zap,
        color: "text-yellow-600",
        visible: true,
        component: LiveWorkMeasuresEditor,
      },
      {
        key: "powerOutageMeasures",
        label: "停电作业措施",
        description: "适用于需要停电的电力线路跨越。",
        icon: Zap,
        color: "text-red-600",
        visible: true,
        component: PowerOutageMeasuresEditor,
      },
      {
        key: "roadClosureMeasures",
        label: "封路作业措施",
        description: "适用于跨越高速公路等重要道路。",
        icon: Car,
        color: "text-blue-600",
        visible: true,
        component: RoadClosureMeasuresEditor,
      },
      {
        key: "trafficControlMeasures",
        label: "交通管制措施",
        description: "适用于跨越铁路。",
        icon: Train,
        color: "text-indigo-600",
        visible: true,
        component: TrafficControlMeasuresEditor,
      },
      {
        key: "navigationControlMeasures",
        label: "停航作业措施",
        description: "适用于跨越通航河流。",
        icon: Ship,
        color: "text-cyan-600",
        visible: true,
        component: NavigationControlMeasuresEditor,
      },
    ];
  }, [crossingPoint, project]);

  const currentConfig = scheme.specialMeasuresConfig || {};
  const selectedMeasures = measureOptions.filter(
    (option) => option.visible && currentConfig[option.key]
  );

  return (
    <div className="space-y-6">
      <Alert>
        <Info className="h-4 w-4" />
        <AlertTitle>专项措施说明</AlertTitle>
        <AlertDescription>
          请先选择需要的措施类型，然后配置具体内容。
        </AlertDescription>
      </Alert>

      {/* 措施选项配置区 */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Settings className="w-5 h-5 text-blue-600" />
            专项措施配置
          </CardTitle>
          <CardDescription>
            选择本次施工需要的专项措施类型，系统将显示相应的配置选项
          </CardDescription>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-1 gap-4">
            {measureOptions.map(
              (option) =>
                option.visible && (
                  <div
                    key={option.key}
                    className={`flex items-center justify-between p-3 border rounded-lg transition-colors ${
                      currentConfig[option.key]
                        ? "border-blue-200 bg-blue-50"
                        : "border-gray-200 hover:bg-gray-50"
                    }`}
                  >
                    <div className="flex items-start gap-3">
                      <option.icon
                        className={`w-5 h-5 ${
                          option.color || "text-gray-500"
                        } mt-1`}
                      />
                      <div>
                        <Label
                          htmlFor={option.key}
                          className="font-medium text-gray-800"
                        >
                          {option.label}
                        </Label>
                        <p className="text-xs text-gray-500">
                          {option.description}
                        </p>
                      </div>
                    </div>
                    <Switch
                      id={option.key}
                      checked={!!currentConfig[option.key]}
                      onCheckedChange={() => handleMeasureToggle(option.key)}
                    />
                  </div>
                )
            )}
          </div>
        </CardContent>
      </Card>

      {/* 详细配置内容区 */}
      {selectedMeasures.length > 0 && (
        <div className="space-y-4">
          {selectedMeasures.map((measureType) => {
            const MeasureComponent = measureType.component;
            return (
              <Card
                key={measureType.key}
                className="border-blue-200 bg-blue-50"
              >
                <CardHeader className="pb-3">
                  <CardTitle className="flex items-center gap-2 text-base">
                    <measureType.icon
                      className={`w-5 h-5 ${measureType.color}`}
                    />
                    {measureType.label}
                  </CardTitle>
                </CardHeader>
                <CardContent className="pt-0">
                  <MeasureComponent
                    scheme={scheme}
                    onUpdate={handleLocalSchemeUpdate}
                    crossingPoint={crossingPoint}
                  />
                </CardContent>
              </Card>
            );
          })}
        </div>
      )}
    </div>
  );
}

export default function MeasuresManager({
  scheme,
  onUpdate,
  crossingPoint,
  project,
  isLoading,
}) {
  const [topLevelTab, setTopLevelTab] = useState("riskIdentification");

  const handleChildUpdate = (updatedData) => {
    onUpdate({ ...scheme, ...updatedData });
  };

  return (
    <div className="space-y-6">
      <Tabs
        value={topLevelTab}
        onValueChange={setTopLevelTab}
        className="w-full"
      >
        <TabsList className="grid w-full grid-cols-4">
          <TabsTrigger value="riskIdentification">
            风险辨识与控制措施
          </TabsTrigger>
          <TabsTrigger value="comprehensive">方案级措施</TabsTrigger>
          <TabsTrigger value="specialMeasures">专项措施</TabsTrigger>
          <TabsTrigger value="stepLevel">步骤级措施</TabsTrigger>
        </TabsList>

        <TabsContent value="riskIdentification" className="mt-6">
          <RiskControlManager
            scheme={scheme}
            onUpdate={handleChildUpdate}
            crossingPoint={crossingPoint}
            project={project}
          />
        </TabsContent>

        <TabsContent value="comprehensive" className="mt-6">
          <SchemeLevelMeasuresManager
            scheme={scheme}
            onUpdate={handleChildUpdate}
          />
        </TabsContent>

        <TabsContent value="specialMeasures" className="mt-6">
          <SpecialMeasuresManager
            scheme={scheme}
            crossingPoint={crossingPoint}
            project={project} // Pass project prop
            onUpdate={handleChildUpdate}
          />
        </TabsContent>

        <TabsContent value="stepLevel" className="mt-6">
          <div className="space-y-6">
            <Alert>
              <Lightbulb className="h-4 w-4" />
              <AlertTitle>信息提示</AlertTitle>
              <AlertDescription>
                此为步骤级措施的只读汇总视图。如需编辑，请前往【施工步骤】标签页完成操作。
              </AlertDescription>
            </Alert>

            {isLoading ? (
              <p>加载中...</p>
            ) : !scheme.constructionSteps ||
              scheme.constructionSteps.length === 0 ? (
              <Card className="text-center py-12">
                <CardContent>
                  <Settings className="w-16 h-16 text-gray-300 mx-auto mb-4" />
                  <h3 className="text-lg font-semibold text-gray-900 mb-2">
                    暂无施工步骤
                  </h3>
                  <p className="text-gray-500">
                    请先在"施工步骤"标签页中添加施工步骤。
                  </p>
                </CardContent>
              </Card>
            ) : (
              <div className="space-y-6">
                {scheme.constructionSteps.map((step, stepIndex) => (
                  <Card key={step.id || stepIndex} className="shadow-sm">
                    <CardHeader className="pb-4">
                      <CardTitle className="flex items-center gap-2">
                        <Badge
                          variant="outline"
                          className="bg-blue-50 text-blue-700"
                        >
                          步骤 {step.stepOrder}
                        </Badge>
                        <span>{step.stepName}</span>
                      </CardTitle>
                      {step.description && (
                        <p className="text-sm text-gray-600 mt-2">
                          {step.description}
                        </p>
                      )}
                    </CardHeader>
                    <CardContent>
                      <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                        {/* 技术措施 */}
                        <div className="space-y-3">
                          <div className="flex items-center gap-2">
                            <Wrench className="w-4 h-4 text-blue-600" />
                            <h4 className="font-semibold text-gray-800">
                              技术措施
                            </h4>
                            <Badge variant="secondary" className="text-xs">
                              {(step.technicalMeasures || []).length} 项
                            </Badge>
                          </div>
                          {(step.technicalMeasures || []).length > 0 ? (
                            <ul className="list-disc pl-5 space-y-1 text-sm text-gray-700">
                              {(step.technicalMeasures || []).map(
                                (measure, index) => (
                                  <li key={index}>{measure}</li>
                                )
                              )}
                            </ul>
                          ) : (
                            <p className="text-sm text-gray-500 italic">
                              无技术措施
                            </p>
                          )}
                        </div>

                        {/* 安全措施 */}
                        <div className="space-y-3">
                          <div className="flex items-center gap-2">
                            <Shield className="w-4 h-4 text-red-600" />
                            <h4 className="font-semibold text-gray-800">
                              安全措施
                            </h4>
                            <Badge variant="secondary" className="text-xs">
                              {(step.safetyMeasures || []).length} 项
                            </Badge>
                          </div>
                          {(step.safetyMeasures || []).length > 0 ? (
                            <ul className="list-disc pl-5 space-y-1 text-sm text-gray-700">
                              {(step.safetyMeasures || []).map(
                                (measure, index) => (
                                  <li key={index}>{measure}</li>
                                )
                              )}
                            </ul>
                          ) : (
                            <p className="text-sm text-gray-500 italic">
                              无安全措施
                            </p>
                          )}
                        </div>

                        {/* 质量措施 */}
                        <div className="space-y-3">
                          <div className="flex items-center gap-2">
                            <CheckSquare className="w-4 h-4 text-green-600" />
                            <h4 className="font-semibold text-gray-800">
                              质量措施
                            </h4>
                            <Badge variant="secondary" className="text-xs">
                              {(step.qualityMeasures || []).length} 项
                            </Badge>
                          </div>
                          {(step.qualityMeasures || []).length > 0 ? (
                            <ul className="list-disc pl-5 space-y-1 text-sm text-gray-700">
                              {(step.qualityMeasures || []).map(
                                (measure, index) => (
                                  <li key={index}>{measure}</li>
                                )
                              )}
                            </ul>
                          ) : (
                            <p className="text-sm text-gray-500 italic">
                              无质量措施
                            </p>
                          )}
                        </div>

                        {/* 环保措施 */}
                        <div className="space-y-3">
                          <div className="flex items-center gap-2">
                            <Leaf className="w-4 h-4 text-green-500" />
                            <h4 className="font-semibold text-gray-800">
                              环保措施
                            </h4>
                            <Badge variant="secondary" className="text-xs">
                              {(step.environmentalMeasures || []).length} 项
                            </Badge>
                          </div>
                          {(step.environmentalMeasures || []).length > 0 ? (
                            <ul className="list-disc pl-5 space-y-1 text-sm text-gray-700">
                              {(step.environmentalMeasures || []).map(
                                (measure, index) => (
                                  <li key={index}>{measure}</li>
                                )
                              )}
                            </ul>
                          ) : (
                            <p className="text-sm text-gray-500 italic">
                              无环保措施
                            </p>
                          )}
                        </div>
                      </div>

                      {/* Standard Operation Categories Display */}
                      {(step.standardWorkCategories || []).length > 0 && (
                        <div className="mt-4 pt-4 border-t border-gray-200">
                          <div className="flex items-center gap-2 mb-2">
                            <BookOpen className="w-4 h-4 text-indigo-600" />
                            <h5 className="text-sm font-medium text-gray-700">
                              标准作业类别
                            </h5>
                          </div>
                          <div className="flex flex-wrap gap-2">
                            {(step.standardWorkCategories || []).map(
                              (category) => (
                                <Badge
                                  key={category}
                                  variant="outline"
                                  className="text-xs bg-indigo-50 text-indigo-700 border-indigo-200"
                                >
                                  {category}
                                </Badge>
                              )
                            )}
                          </div>
                        </div>
                      )}
                    </CardContent>
                  </Card>
                ))}
              </div>
            )}
          </div>
        </TabsContent>
      </Tabs>
    </div>
  );
}
